<template>

  <div class="app-container " style="width: 100%;">
    <!--列表工具栏-->
    <vxe-toolbar id="toolbar"
                 :custom="{storage: true}"
                 :export="{}"
    >

      <template v-slot:buttons>
        <el-button size="small" icon="el-icon-circle-plus-outline" @click="insertListening()">新增</el-button>
        <!--        <el-button size="small" icon="el-icon-circle-plus-outline" @click="exportDataEvent()">导出</el-button>-->
        <el-button size="small" icon="el-icon-circle-plus-inline" @click="batchInsertDialog = true">批量导入</el-button>
        <!-- <vxe-button>清除筛选</vxe-button> -->
      </template>
    </vxe-toolbar>


    <vxe-table
      size="small"
      border
      resizable
      :loading="loading"
      :tooltip-config="{theme: 'light'}"
      :data="tableData"
      :start-index="(tablePage.currentPage - 1) * tablePage.pageSize"
      :pager-config="tablePage"

    >
      <vxe-table-column type="index" width="100px" label="序号" align="center">
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </vxe-table-column>

      <vxe-table-column field="userId" title="用户电报ID" width="100px" align="center" show-overflow="tooltip">
        <template slot-scope="scope">
          <span>{{ scope.row.userId }}</span>
        </template>
      </vxe-table-column>
      <vxe-table-column field="userName" title="用户名"
                        show-overflow="tooltip"
                        align="center"
                        width="100px">
        <template slot-scope="scope">
          {{ scope.row.userName }}
        </template>
      </vxe-table-column>
      <vxe-table-column field="userFirstName" title="First Name" width="150px" align="center" show-overflow="tooltip">
        <template slot-scope="scope">
          <span>{{ scope.row.userFirstName }}</span>
        </template>
      </vxe-table-column>
      <vxe-table-column field="userLastName" title="Last Name" width="150px" align="center" show-overflow="tooltip">
        <template slot-scope="scope">
          <span>{{ scope.row.userLastName }}</span>
        </template>
      </vxe-table-column>
      <vxe-table-column field="profile" title="QQ" width="150px" align="center" show-overflow="tooltip">
        <template slot-scope="scope">
          {{ scope.row.qq }}
        </template>
      </vxe-table-column>
      <vxe-table-column field="profile" title="微信" width="150px" align="center" show-overflow="tooltip">
        <template slot-scope="scope">
          {{ scope.row.wechat }}
        </template>
      </vxe-table-column>
      <vxe-table-column field="profile" title="电话" width="150px" align="center" show-overflow="tooltip">
        <template slot-scope="scope">
          {{ scope.row.phoneNumber }}
        </template>
      </vxe-table-column>
      <vxe-table-column field="profile" title="邮箱" width="150px" align="center" show-overflow="tooltip">
        <template slot-scope="scope">
          {{ scope.row.email }}
        </template>
      </vxe-table-column>
      <vxe-table-column field="lastOnline" class-name="status-col"
                        :filters="[{data: []}]"
                        title="最近上线时间" width="200px" align="center">
        <template slot-scope="scope">
          <i class="el-icon-time"/>
          <span>{{ scope.row.lastOnline }}</span>
        </template>
      </vxe-table-column>
      <vxe-table-column field="profile" title="个人简介" width="400px" align="center" show-overflow="tooltip">
        <template slot-scope="scope">
          {{ scope.row.profile }}
        </template>
      </vxe-table-column>
      <vxe-table-column align="center" title="入库时间" width="200px" sortable>
        <template slot-scope="scope">
          <i class="el-icon-time"/>
          <span>{{ scope.row.gmtCreate }}</span>
        </template>
      </vxe-table-column>
      <vxe-table-column align="center" title="更新时间" width="200px" sortable>
        <template slot-scope="scope">
          <i class="el-icon-time"/>
          <span>{{ scope.row.gmtModify }}</span>
        </template>
      </vxe-table-column>

      <!--列表删除编辑按钮-->
      <vxe-table-column align="center" fixed="right" title="操作" min-width="330px">
        <template v-slot="{ row}">
          <el-button type="info" icon="el-icon-document" size="mini" @click="showRecentlySpoken({row})"
                     style="width: 28%">最近发言
          </el-button>
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="editOne({row})" style="width:22%">编辑
          </el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteSensitiveUser({row})"
                     style="width: 22%">删除
          </el-button>
        </template>
      </vxe-table-column>
    </vxe-table>
    <!--分页功能支持-->
    <vxe-pager
      perfect
      size="mini"
      :loading="loading"
      :current-page="tablePage.currentPage"
      :page-size="tablePage.pageSize"
      :total="tablePage.total"
      :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
      @page-change="handlePageChange">
    </vxe-pager>

    <vxe-modal v-model="showDetails" title="敏感用户" width="800" height="400" resize>
      <template>敏感用户</template>
    </vxe-modal>

    <!--新增频道-->
    <el-dialog v-if="!form.isUpdate" title="添加敏感用户" :visible.sync="dialogFormVisible" width="80%">
      <el-form ref="form" :model="form" :rules="rules" >
        <el-input type="hidden" v-model="form.id" autocomplete="off"/>
        <el-form-item label="用户电报ID" :label-width="formLabelWidth" prop="userId" >
          <el-input v-model.number="form.userId" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="用户名" :label-width="formLabelWidth">
          <el-input v-model="form.userName" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="first name" :label-width="formLabelWidth">
          <el-input v-model="form.userFirstName"/>
        </el-form-item>
        <el-form-item label="last name" :label-width="formLabelWidth">
          <el-input v-model="form.userLastName"/>
        </el-form-item>
        <el-form-item label="个人简介" :label-width="formLabelWidth">
          <el-input type="textarea" v-model="form.profile"/>
        </el-form-item>
        <el-form-item label="头像路径" :label-width="formLabelWidth">
          <el-input v-model="form.profilePhoto"/>
        </el-form-item>
        <el-form-item label="最近上线" :label-width="formLabelWidth">
          <el-input v-model="form.lastOnline"/>
        </el-form-item>
      </el-form>

      <!--新增页面的确认按钮-->
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addSensitiveUser()">添 加</el-button>
      </div>

    </el-dialog>
    <!--更新频道-->
    <el-dialog v-else title="修改敏感用户" :visible.sync="dialogFormVisible" width="80%" >
      <el-form ref="form" :model="form">
        <el-input type="hidden" v-model="form.id" autocomplete="off"/>
        <el-form-item label="用户电报ID" :label-width="formLabelWidth">
          <el-input v-model="form.userId" autocomplete="off" readonly="readonly"/>
        </el-form-item>
        <el-form-item label="用户名" :label-width="formLabelWidth">
          <el-input v-model="form.userName" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="first name" :label-width="formLabelWidth">
          <el-input v-model="form.userFirstName"/>
        </el-form-item>
        <el-form-item label="last name" :label-width="formLabelWidth">
          <el-input v-model="form.userLastName"/>
        </el-form-item>
        <el-form-item label="个人简介" :label-width="formLabelWidth">
          <el-input type="textarea" v-model="form.profile"/>
        </el-form-item>
        <el-form-item label="头像路径" :label-width="formLabelWidth">
          <el-input v-model="form.profilePhoto"/>
        </el-form-item>
        <el-form-item label="最近上线" :label-width="formLabelWidth">
          <el-input v-model="form.lastOnline"/>
        </el-form-item>
      </el-form>

      <!--更新和新增页面的确认按钮-->
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateSensitiveUser()">确 定</el-button>
      </div>

    </el-dialog>

    <!--批量导入对话框-->
    <el-dialog
      title="批量导入"
      :visible.sync="batchInsertDialog"
      width="40%">
      <el-input
        type="textarea"
        :autosize="{ minRows: 4, maxRows: 10}"
        placeholder="请输入用户ID 每行一个"
        v-model="batchInsertData">
      </el-input>
      <!--更新和新增页面的确认按钮-->
      <div slot="footer" class="dialog-footer">
        <el-button @click="batchInsertDialog  = false">取 消</el-button>
        <el-button type="primary" @click="basertInsert()">导 入</el-button>
      </div>
    </el-dialog>


    <!--最近发言表格-->
    <el-dialog :visible.sync="spokenFormVisible" width="80%" >
      <vxe-table
        size="small"
        resizable
        :loading="spokenLoading"
        :tooltip-config="{theme: 'light'}"
        :data="recentlySpokenData"
        :start-index="(recentlySpoken.currentPage - 1) * recentlySpoken.pageSize"
        :pager-config="recentlySpoken"
      >
        <vxe-table-column field="msgId" title="消息ID" align="center" width="8%" show-overflow="title">
          <template slot-scope="scope">
            <span>{{ scope.row.msgId }}</span>
          </template>
        </vxe-table-column>
        <vxe-table-column field="username" title="发送者"
                          align="center"
                          width="10%" show-overflow="title">
          <template slot-scope="scope">
            {{ scope.row.senderFirstName }} {{ scope.row.senderLastName }}
          </template>
        </vxe-table-column>
        <vxe-table-column field="msgText" title="消息内容" align="center" show-overflow="title">
          <template slot-scope="scope">
            {{ scope.row.msgText }}
          </template>
        </vxe-table-column>
        <vxe-table-column field="chatTitle" title="频道\群组" align="center" width="15%" show-overflow="title">
          <template slot-scope="scope">
            {{ scope.row.chatTitle }}
          </template>
        </vxe-table-column>
        <vxe-table-column field="dateTime" align="center" title="发送时间" sortable width="200px"
                          :filters="[{data: []}]"
                          :filter-render="{name: 'ElDatePicker', props: {type: 'datetimerange', rangeSeparator: '至', startPlaceholder: '开始日期', endPlaceholder: '结束日期'}}" show-overflow="title">
          <template slot-scope="scope">
            <i class="el-icon-time"/>
            <span>{{ scope.row.dateTime }}</span>
          </template>
        </vxe-table-column>
      </vxe-table>
      <!--分页功能支持-->
      <vxe-pager
        perfect
        size="mini"
        :loading="spokenLoading"
        :current-page="recentlySpoken.currentPage"
        :page-size="recentlySpoken.pageSize"
        :total="recentlySpoken.total"
        :layouts="recentlySpoken.layouts"
        @page-change="handleSpokenPageChange">
      </vxe-pager>
    </el-dialog>
  </div>
</template>

<script>
  import * as tableApi from '@/api/table'
  import Vue from 'vue'
  import 'xe-utils'
  import VXETable from 'vxe-table'
  import VXETablePluginElement from 'vxe-table-plugin-element'
  import 'vxe-table-plugin-element/dist/style.css'

  Vue.use(VXETable)

  VXETable.use(VXETablePluginElement)
  // import demo from '@/views/table/dialogForm.vue'
  let emptyString =  '-'

  export default {
    filters: {
      statusFilter(status) {
        const statusMap = {
          published: 'success',
          draft: 'gray',
          deleted: 'danger'
        }
        return statusMap[status]
      }
    },

    data() {
      return {
        batchInsertData: '',
        showDetails: false,
        loading: false,
        spokenLoading: false,
        tableData: [],
        tablePage: {
          align: 'left',
          currentPage: 1,
          pageSize: 10,
          total: 0,
          pageSizes: [10, 20, 50, 100, 200, 500],
          layouts: ['Sizes', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total'],
          perfect: true,
        },
        //表格数据
        recentlySpokenData: [],
        //表格配置
        recentlySpoken: {
          align: 'left',
          currentPage: 1,
          pageSize: 10,
          total: 0,
          pageSizes: [10, 20, 50, 100, 200, 500],
          layouts: ['Sizes', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total'],
          perfect: true,
          userId: ''
        },
        dialogFormVisible: false,
        spokenFormVisible: false,
        batchInsertDialog: false,
        deleteId: "",
        refresh: true, // 刷新按钮
        import: true, // 导入按钮
        export: true,
        form: {
          userId: '',
          userName: '',
          userFirstName: '',
          userLastName: '',
          profile: '',
          profilePhoto: '',
          lastOnline: '',
          isUpdate: false
        },
        formLabelWidth: '100px',
        listLoading: true,
        rules: {
          userId: [
            { required: true, message: '请输入用户电报ID', trigger: 'blur' },
            { type: 'number', message: '请输入正确的用户电报ID', trigger: 'blur' }
          ]
        }
      }
    },
    created() {
      this.loading = true
      setTimeout(() => {
        this.fetchData(1, 10)
      }, 5)
    },
    methods: {
      fetchData(currentPage, pageSize) {
        let data = {"currentPage": currentPage, "pageSize": pageSize}
        tableApi.getSensitiveUsers(data).then(response => {
          let array = response.data
          //填充空数据为默认字符串 ‘暂无’
          array.forEach(function (item,index) {
              for (let key in item){
                if (item.hasOwnProperty(key) && !item[key]){
                  item[key] = emptyString;
                }
              }
          })
          this.tableData = array
          this.listLoading = false
          this.loading = false
          this.tablePage.total = response.total;
          this.tablePage.currentPage = response.currentPage
          this.tablePage.pageSize = response.pageSize
        })
      },
      fetchSpokenData(currentPage, pageSize) {
        this.spokenLoading = true
        //清空一下页面效果更好
        this.recentlySpokenData = []
        let userId = this.recentlySpoken.userId
        let data = {"currentPage": currentPage, "pageSize": pageSize, "userId": userId}
        tableApi.getSpoken(data).then(response => {
          this.recentlySpokenData = response.data
          this.recentlySpoken.total = response.total;
          this.recentlySpoken.currentPage = response.currentPage
          this.recentlySpoken.pageSize = response.pageSize
          this.spokenLoading = false
        })
      },
      resetDateFilter() {
      },
      clearFilter() {
      },
      exportDataEvent() {
        this.$refs.xTable.openExport({
          // 默认勾选源
          original: true
        })
      },
      importDataEvent() {
        this.$refs.xTable.importData()
      },
      handleSizeChange(val) {
        this.pageSize = val;
        this.currentPage = 1;
        this.fetchData(1, val);
      },
      handleCurrentChange(val) {
        this.currentPage = val;
        this.fetchData(val, this.pageSize);
      },
      filterHandler(val) {
        console.info(val)
      },/*,
      chatNameFilter(){
        this.getfilter= [{text: '2016-05-01', value: '2016-05-01'}, {text: '2016-05-02', value: '2016-05-02'}, {text: '2016-05-03', value: '2016-05-03'}, {text: '2016-05-04', value: '2016-05-04'}]
      }*/
      formatterStatus({cellValue}) {
        let item = this.sexList.find(item => item.value === cellValue)
        return item ? item.label : ''
      },
      showDetailEvent() {
        // this.selectRow = row
        this.showDetails = true
      },
      filterTitlMethod({option, row}) {
        console.info(option.data)
        return row.chatTitle === option.data
      },
      searchEvent() {
        this.tablePage.currentPage = 1
        this.findList()
      },
      handlePageChange({currentPage, pageSize}) {
        this.tablePage.pageSize = pageSize
        this.loading = true
        this.fetchData(currentPage, pageSize)
      },
      addSensitiveUser() {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            //组装数据 ，进行提交
            var data = {"data": this.form}
            tableApi.addSensitiveUser(data).then(response => {
              if (response.code === 200) {
                this.dialogFormVisible = false
                this.$message({
                  showClose: true,
                  message: response.msg,
                  type: 'success',
                  duration: 1000
                });
                this.fetchData(this.tablePage.currentPage, this.tablePage.pageSize)
              } else {
                this.$message({
                  showClose: true,
                  message: response.msg,
                  type: 'error',
                  duration: 1000
                });
              }

            })
          } else {
            return false;
          }
        });

      },

      insertListening() {
        this.form.isUpdate = false
        this.form.lastOnline = null
        this.form.userFirstName = null
        this.form.userLastName = null
        this.form.profilePhoto = null
        this.form.userName = null
        this.form.id = null
        this.form.userId = null
        this.form.profile = null
        this.dialogFormVisible = true
      },
      //对单独一条数据进行编辑（只能添加备注）
      editOne({row}) {

        this.form.userId = row.userId
        this.form.userName = row.userName
        this.form.userFirstName = row.userFirstName
        this.form.userLastName = row.userLastName
        this.form.profile = row.profile
        this.form.profilePhoto = row.profilePhoto
        this.form.lastOnline = row.lastOnline
        this.form.id = row.id
        this.form.isUpdate = true
        //将空字符串设为null
        for (let key in this.form){
          if (this.form.hasOwnProperty(key) && this.form[key] === emptyString){
            this.form[key] = null;
          }
        }
        this.dialogFormVisible = true
      },
      updateSensitiveUser(data) {
        data = {
          "id": this.form.id,
          "userName": this.form.userName,
          "userFirstName": this.form.userFirstName,
          "userLastName": this.form.userLastName,
          "userId": this.form.userId,
          "profile": this.form.profile,
          "profilePhoto": this.form.profilePhoto,
          "lastOnline": this.form.lastOnline
        }
        tableApi.updateSensitiveUser(data).then(response => {
          console.info(response)
          if (response.code === 200) {
            this.$message({
              showClose: true,
              message: response.msg,
              type: 'success',
              duration: 1000
            });
            this.fetchData(this.tablePage.currentPage, this.tablePage.pageSize)
          } else {
            this.$message({
              showClose: true,
              message: response.msg,
              type: 'error',
              duration: 1000
            });
          }
          this.dialogFormVisible = false
        });
      },
      deleteSensitiveUser({row}) {
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          tableApi.deleteSensitiveUser(row.id).then(response => {
            console.info(response)
            if (response.code === 200) {
              this.$message({
                showClose: true,
                message: response.msg,
                type: 'success',
                duration: 1000
              });
              this.fetchData(this.tablePage.currentPage, this.tablePage.pageSize)
            } else {
              this.$message({
                showClose: true,
                message: response.msg,
                type: 'error',
                duration: 1000
              });
            }
          });
        }).catch(() => {
          // this.$message({
          //   title: '提示',
          //   message: '取消删除',
          //   type: 'info',
          //   duration: 1000
          // });
        });
      },
      //查看最近发言
      showRecentlySpoken({row}) {
        this.spokenFormVisible = true
        this.recentlySpoken.userId = row.userId
        this.fetchSpokenData(1, 10)
      },
      //最近发言翻页
      handleSpokenPageChange({currentPage, pageSize}) {
        this.recentlySpoken.pageSize = pageSize
        this.fetchSpokenData(currentPage, pageSize)
      },
      //批量导入
      basertInsert() {
        tableApi.batchInsertSensitiveUser({data: this.batchInsertData}).then(response => {
          if (response.code === 200) {
            this.$message({
              showClose: true,
              message: response.msg,
              type: 'success',
              duration: 1000
            });
            this.batchInsertData = ''
            this.batchInsertDialog = false
            this.fetchData(this.tablePage.currentPage, this.tablePage.pageSize)
          } else {
            this.$message({
              showClose: true,
              message: response.msg,
              type: 'error',
              duration: 1000
            });
          }
        });
      }
    }
  }
</script>
